package com.aiyige.page.my.wallet;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.eventbus.EventSetWalletPwdSuccess;
import com.aiyige.model.User;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.VerifyCodeManager;
import com.aiyige.utils.widget.PayPwdEditText;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.vondear.rxtools.RxKeyboardTool;
import com.vondear.rxtools.RxTool;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 设置钱包-设置密码
 */
@Route(path = ARouterConfig.WalletSetPwdPage2, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class WalletSetPwdPage2 extends BaseActivity {


    @BindView(R.id.tv_finish)
    TextView tvFinish;
    @BindView(R.id.tv_setpwd_hint)
    TextView tvSetpwdHint;
    @BindView(R.id.pay_pwd_edittext)
    PayPwdEditText payPwdEdittext;

    @Autowired
    String code;

    @Autowired
    String password1;

    @Autowired
    public boolean isChangePassword = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_wallet_set_password2);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        initTitleLayout(getString(isChangePassword?R.string.change_wallet_password:R.string.set_wallet_password));
        /**
         * @param bgdrawable 背景drawable
         * @param pwdlength 密码长度
         * @param splilinewidth 分割线宽度
         * @param splilinecolor 分割线颜色
         * @param pwdcolor 密码字体颜色
         * @param pwdsize 密码字体大小
         */
        payPwdEdittext.initStyle(R.drawable.edit_num_bg, 6, 0.5f, R.color.zwcolor_gray_bfbfbf, R.color.zwcolor_black_111111, 32);
        payPwdEdittext.setOnTextFinishListener(new PayPwdEditText.OnTextFinishListener() {
            @Override
            public void onFinish(String str) {//密码输入完后的回调
                if (str.equals(password1)) {

                    request();
                } else {
                    ToastX.show("两次密码不一致，请重新输入");
                }

            }
        });
        payPwdEdittext.setFocus();
        RxKeyboardTool.showSoftInput(this,payPwdEdittext.getEditText());
    }

    private void request() {
        User user = new User();
        user.setWalletPassword(new User.WalletPassword(RxTool.Md5(password1), AccountUtil.getCurrentUser().getMobile(), code));
        ApiManager.getService()
                .userCenterUsers(String.valueOf(AccountUtil.getCurrentUser().getId()), user)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        tvFinish.setVisibility(View.VISIBLE);
                        try {
                            if (response.code() != ResponseCode.CREATED) {
                                throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                            } else {
                                VerifyCodeManager.getInstance().cancel();
                                String json = RetrofitUtil.getResponseBodyAsString(response);
                                User tempUser = JSON.parseObject(json, User.class);
                                User user = AccountUtil.getCurrentUser();
                                user.setWalletPassword(tempUser.getWalletPassword());
                                user.setHasWalletPassword(tempUser.isHasWalletPassword());
                                AccountUtil.updateCurrentUser(user);
                                ToastX.show(isChangePassword?R.string.wallet_change_password_success:R.string.wallet_reset_password_success);
                                EventBus.getDefault().post(new EventSetWalletPwdSuccess());
                                finish();
                            }

                        } catch (Exception e) {
                            onFailure(call, e);
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        tvFinish.setVisibility(View.VISIBLE);
                        ToastX.show(t.getMessage());
                    }
                });


    }


    @OnClick({R.id.tv_finish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_finish:
                request();
                break;
        }
    }

}
